package com.hmall.search.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.feign.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public List<String> getSuggestion(String key) {
        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();

        SuggestBuilder suggestBuilder = new SuggestBuilder();
        source.suggest(
                suggestBuilder.addSuggestion(
                        "mySuggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(key)
                                .skipDuplicates(true)
                                .size(10)
                )
        );

        //2。执行请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            List<String> list = new ArrayList<>();
            //3.解析响应结果
            Suggest suggest = response.getSuggest();
            CompletionSuggestion completionSuggestion = suggest.getSuggestion("mySuggestion");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        Integer page = params.getPage(); //页码
        Integer pageSize = params.getSize(); // 每页条数

        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        //构建所有的请求参数
        SearchSourceBuilder source = request.source();

        //获取排序参数
        String sortBy = params.getSortBy();
        if ("sold".equals(sortBy)) {
            source.sort(sortBy, SortOrder.DESC);
        }
        if ("price".equals(sortBy)) {
            source.sort(sortBy, SortOrder.ASC);
        }

        basicQuery(params, source);

        source.from((page - 1) * pageSize);
        source.size(pageSize);

        PageDTO<ItemDoc> pageDTO = handleResult(request);
        return pageDTO;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        Map<String, List<String>> map = new HashMap<>();

        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();

        basicQuery(params, source);
        //聚合条件
        source.aggregation(
                AggregationBuilders.terms("categoryAgg")
                        .field("category")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand")
                        .size(20)
        );
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Aggregations aggregations = response.getAggregations();

            List<String> brandList = getAggResult(aggregations, "brandAgg");
            List<String> categoryAgg = getAggResult(aggregations, "categoryAgg");

            map.put("category", categoryAgg);
            map.put("brand", brandList);

            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private List<String> getAggResult(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<String> list = new ArrayList<>();

        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    private void basicQuery(RequestParams params, SearchSourceBuilder source) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //关键字key  match搜索  must算分
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //高亮三要素
            highlightBuilder.field("name");
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);

        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }

        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }

        // 新增 算分查询条件
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        ).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY);
        source.query(functionScoreQuery);

    }

    private PageDTO<ItemDoc> handleResult(SearchRequest request) {
        //执行请求，得到响应结果
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
            //解析响应结果
            SearchHits searchHits = response.getHits();
            //查询的总记录数
            long value = searchHits.getTotalHits().value;
            List<ItemDoc> list = new ArrayList<>();
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    HighlightField highlightField = highlightFields.get("name");
                    String nameHighResult = highlightField.getFragments()[0].string();
                    itemDoc.setName(nameHighResult);
                }
                list.add(itemDoc);
            }
            return new PageDTO(value, list);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
